package com.ruoyi.server.login;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.resource.mapper.FriendMapper;
import com.ruoyi.resource.mapper.GroupMapper;
import com.ruoyi.server.person.PassageWayUser;
import com.ruoyi.server.pkg.SendMsg;
import com.ruoyi.server.read.PrivateReader;
import com.ruoyi.server.utils.AddUtil;
import com.ruoyi.server.utils.OnlineUtil;
import io.netty.channel.*;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND;

/**
 *  登录认证器
 *
 * @author OpenACloud
 * @create 2024/6/3 22:00
 */
@Component
@ChannelHandler.Sharable
public class LoginReader extends SimpleChannelInboundHandler<FullHttpRequest> {

    @Resource
    private RedisCache redisCache;
    @Resource
    private GroupMapper groupMapper;
    @Resource
    private FriendMapper friendMapper;


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("LoginReader ExceptionCaught");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {

        HttpHeaders headers = req.headers();
        String token = headers.get("Authorization");
        LoginUser userOnline = redisCache.getCacheObject(CacheConstants.LOGIN_TOKEN_KEY + token);
        if(Objects.isNull(userOnline)) {
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(req.protocolVersion(), NOT_FOUND, ctx.alloc().buffer(0)));
            return;
        }


        Set<Long> meGroup = groupMapper.findMeGroup(userOnline.getUserId());
        Set<Long> meFriend = friendMapper.findMeFriend(userOnline.getUserId());

        ctx.attr(OnlineUtil.SEND_ID).set(userOnline.getUserId());
        ctx.attr(OnlineUtil.PASSAGE_WAR_USER).set(new PassageWayUser(userOnline));
        ctx.attr(OnlineUtil.USER_FRIEND).set(meFriend);
        ctx.attr(OnlineUtil.USER_GROUP).set(meGroup);

        ctx.fireChannelRead(req.retain());
    }

    private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
        ChannelFuture sendResult = ctx.writeAndFlush(res).addListener(ChannelFutureListener.CLOSE);
    }

}
